#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
 
int
main(int argc, char **argv)
{
    int fd_in, fd_out;
    char *buf;
    int bufsize=1024;
 
    if (argc<3) {
        fprintf(stderr, "Usage: %s INPUT OUTPUT [BUFSIZE]\n", argv[0]);
        exit(1);
    }
 
    if (argv[1][0]=='-' && argv[1][1]==0) {
        fd_in = 0;
    } else {
        fd_in = open(argv[1], O_RDONLY);
        if (fd_in<0) {
            perror("open()");
            exit(1);
        }
    }
 
    if (argv[2][0]=='-' && argv[2][1]==0) {
        fd_out = 1;
    } else {
        fd_out = open(argv[2], O_WRONLY|O_CREAT|O_TRUNC, 0600);
        if (fd_out<0) {
            perror("open()");
            exit(1);
        }
    }
 
    if (argc>3) {
        bufsize = atoi(argv[3]);
    }
 
    buf = malloc(bufsize);
    while(1) {
        ssize_t len, ret, pos;
 
        len = read(fd_in, buf, bufsize);
        if (len==0) {
            break;
        }
        pos = 0;
        while (len>0) {
            ret = write(fd_out, buf+pos, len);
            if (ret<0) {
                perror("write()");
                exit(1);
            }
            len -= ret;
            pos += ret;
        }
    }
    free(buf);
 
    if (fd_in != 0) {
        close(fd_in);
    }
    if (fd_out != 1) {
        close(fd_out);
    }
 
    return 0;
}